package com.chuangyang.fixboxmaster.service;

import android.content.Intent;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.Listener;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.chuangyang.fixboxlib.utils.LogUtils;
import com.chuangyang.fixboxlib.utils.StringUtils;
import com.chuangyang.fixboxmaster.AppData;
import com.chuangyang.fixboxmaster.bean.BaseInfo;
import com.chuangyang.fixboxmaster.ui.LoginActivity;
import com.chuangyang.fixboxmaster.utils.PrefUtils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * Volley adapter for JSON requests that will be parsed into Java objects by Gson.
 */
public class GsonRequest<T> extends Request<T> {
    public static String TAG=GsonRequest.class.getSimpleName();
    public static final int DEFAULT_TIMEOUT_MS = 0;
    public static final int DEFAULT_MAX_RETRIES = 0;
    public static final float DEFAULT_BACKOFF_MULT = 1f;
    private final Gson gson = new Gson();
    private final Class<T> clazz;
    private final Listener<T> listener;
    private static  Map<String, String> headers = new HashMap<>();
    private Map<String, String> params = new HashMap<>();

    public static final int SUCCESS = 1; //正确返回结果
    public static final int ACCESS_TOKEN_TIME_OUT = -1000; // ACCESS_TOKEN失效
    public static final int ACCESS_TOKEN_NULL = -1001; // ACCESS_TOKEN没有传入



    static {
        String channelId = StringUtils.getMetaData(AppData.getContext()).getString("UMENG_CHANNEL");//获取渠道号
        String model = StringUtils.getDeviceName();
        String osVersion = StringUtils.getDeviceOsVersion();
        String versionCode = StringUtils.getVersionName(AppData.getContext());
        String mobileType = "2";  //手机类型，1表示ios ，2表示android
        String screenSize = StringUtils.getScreenSizeInPx(AppData.getContext());
        headers.put("channelId",channelId);
        headers.put("mobileModel",model);
        headers.put("osVersionCode",osVersion);
        headers.put("appVersionCode",versionCode);
        headers.put("mobileType",mobileType);
        headers.put("screen",screenSize);

    }

    public GsonRequest(String url, HashMap<String, String> params, Class<T> clazz, Listener<T> listener) {
        super(Method.POST, url, errorListener);
        this.params = params;
        this.clazz = clazz;
        this.listener = listener;
        setRetryPolicy();
    }

    public GsonRequest(String url, Class<T> clazz, Listener<T> listener) {
        super(Method.POST, url, errorListener);
        this.clazz = clazz;
        this.listener = listener;
        setRetryPolicy();
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        return headers != null ? headers : super.getHeaders();
    }

    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        if(PrefUtils.getString(PrefUtils.ACCESS_TOKEN)!=null){
            params.put(PrefUtils.ACCESS_TOKEN, PrefUtils.getString(AppData.getContext(),PrefUtils.ACCESS_TOKEN));
        }
        return params;
    }

    private void setRetryPolicy() {
        setRetryPolicy(new DefaultRetryPolicy(DEFAULT_TIMEOUT_MS, DEFAULT_MAX_RETRIES, DEFAULT_BACKOFF_MULT));
    }

    @Override
    protected void deliverResponse(T response) {
        if (response != null) {
            switch (((BaseInfo) response).success) {
                case SUCCESS:
                    listener.onResponse(response);
                    break;
                case ACCESS_TOKEN_TIME_OUT:
                    PrefUtils.putString(AppData.getContext(), PrefUtils.ACCESS_TOKEN, null);
                    Intent intent = new Intent(AppData.getContext(), LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    AppData.getContext().startActivity(intent); // Launch the LoginActivity
                    Toast.makeText(AppData.getContext(), ((BaseInfo) response).msg, Toast.LENGTH_SHORT).show();
                    break;
                case ACCESS_TOKEN_NULL:
                    Toast.makeText(AppData.getContext(), ((BaseInfo) response).msg, Toast.LENGTH_SHORT).show();
                    break;
                default:
                    Toast.makeText(AppData.getContext(), ((BaseInfo) response).msg, Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    }

    @Override
    protected Response<T> parseNetworkResponse(NetworkResponse response) {
        try {
            //  String format = HttpHeaderParser.parseCharset(response.headers);
            String format = "UTF-8";
            String json = new String(response.data, format);
            return Response.success(
                    gson.fromJson(json, clazz), HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JsonSyntaxException e) {
            return Response.error(new ParseError(e));
        }
    }

    public static Response.ErrorListener errorListener = new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            if (error instanceof ParseError) {
                LogUtils.LOGE(TAG,error.getMessage());
                Toast.makeText(AppData.getContext(), "解析错误" + error.getMessage(), Toast.LENGTH_LONG).show();
            } else if (error instanceof NetworkError) {
                LogUtils.LOGE(TAG, error.getMessage());
                Toast.makeText(AppData.getContext(), "网络错误 " + error.getMessage(), Toast.LENGTH_LONG).show();
            } else if (error instanceof ServerError) {
                try {
                    LogUtils.LOGE(TAG,error.getMessage());
                    Toast.makeText(AppData.getContext(), "服务端错误，返回状态码为 : " + error.networkResponse.statusCode + ",  : " + new String(error.networkResponse.data, "UTF-8"), Toast.LENGTH_LONG).show();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }else if(error instanceof TimeoutError){
                LogUtils.LOGE(TAG,error.getMessage());
                Toast.makeText(AppData.getContext(), "读取连接超时，请稍后重试", Toast.LENGTH_LONG).show();
            }
             else {
                LogUtils.LOGE(TAG,error.getMessage());
                Toast.makeText(AppData.getContext(), "未知错误" + error.getMessage(), Toast.LENGTH_LONG).show();
            }
        }
    };
}